package com.jhmk.jhecis.components;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jhmk.jhecis.config.JSRegister;
import com.jhmk.jhecis.domain.InterfaceTool;
import com.jhmk.jhecis.domain.common.R;
import com.jhmk.jhecis.domain.vo.ScriptContent;
import com.jhmk.jhecis.interceptor.GlobalResponseInterceptor;
import com.jhmk.jhecis.service.InterfaceToolService;
import jakarta.annotation.Resource;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**所有的核心在这
 * Js脚本执行类
 */
@Component
public class JsEngine {

    private static final Logger log = LoggerFactory.getLogger(GlobalResponseInterceptor.class);

    @Resource
    InterfaceToolService interfaceToolService;

    @Resource
    JSRegister jsRegister;
    /**
     * 传入脚本编码与脚本参数，执行脚本，获取结果
     * @param input
     * @return
     */
    public R<String> execJs(ScriptContent input){
        //1.通过编码获取脚本数据
        QueryWrapper<InterfaceTool> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(InterfaceTool::getInterfacecode,input.getInterfaceCode());
        InterfaceTool itModel= interfaceToolService.selectJavascriptcodeAndFunctionnameByInterfacecode(input.getJavaScriptCode());
        if (itModel==null)
            return R.fail("未找到配置的脚本！");
        //2.执行脚本
        try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
            // 将Java对象,绑定到上下文
            context.getBindings("js").putMember("JSRegister", jsRegister);
            // 执行包含JavaScript函数生成
            Source source = Source.newBuilder("js",itModel.getJavascriptcode(), itModel.getFunctionname()).build();
            context.eval(source);
            // 调用JavaScript函数并传递参数
            Object result = context.getBindings("js").getMember(itModel.getFunctionname()).execute(input.getData());
            return R.ok(result.toString());
        }
        catch (Exception e) {
           return R.fail("脚本执行失败");
        }
    }

    /**
     * 使用传入的脚本执行
     * @return
     */
    public R<String> execCacheJs(ScriptContent input){
        if (input==null ||  StrUtil.isEmpty(input.getJavaScriptCode()) || StrUtil.isEmpty(input.getFunctionName()))
            return R.fail("脚本内容或入口函数为空");
        //2.执行脚本
        try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
            // 将Java对象,绑定到上下文
            context.getBindings("js").putMember("JSRegister", jsRegister);
            //脚本函数生成
            Source source = Source.newBuilder("js",input.getJavaScriptCode(), input.getJavaScriptCode()).build();
            context.eval(source);
            //函数入参
            String parm="";
            if(input.getData()!=null)
                parm = input.getData();
            //调用函数并传递参数
            Object result = context.getBindings("js").getMember(input.getFunctionName()).execute(parm);
            return R.ok(result.toString());
        }
        catch (Exception e) {
            return R.fail("脚本执行失败");
        }
    }
}
